import { Login, LoginParam } from '@/domain/correction/types/jobs/login';
import { reactive, inject, provide } from 'vue';
import { ConsoleLogger } from '@/utils/debug-log';
import { getCurrentUser, userLogin, register } from '../api/login';
import { router } from '@/project/correction/phoneOa/router';
import { BaseResponse } from '../api/index';
const console = new ConsoleLogger('登陆');
const useUserInfoSymbol = Symbol('useUserinfo store');

export interface IUserInfoState {
  isLoginStatus: boolean;
  userInfo?: Partial<Login>;
}

export interface IUseUserInfoStoreFn {
  (): IUseUserInfoStore;
  __CurrentStore?: IUseUserInfoStore;
}

export interface IUseUserInfoStore {
  state: IUserInfoState;
  init: () => void;
  myuserLogin: (param: LoginParam) => Promise<BaseResponse<Login>>;
  myuserRegister: (param: LoginParam) => Promise<BaseResponse<Login>>;
}
/**
 *  * useUserInfoStore 用户hooks.
 * @function
 * @params {IUserInfoState} userState - 用户信息.
 * @returns store extend IUseUserInfoStore
 */
export const useUserInfoProvide: () => IUseUserInfoStore = () => {
  const state = reactive<IUserInfoState>({
    isLoginStatus: false,
    userInfo: undefined
  });
  const gainUserInfo = async () => {
    let userInfo = await getCurrentUser();
    state.userInfo = userInfo.data?.teacher_id ? userInfo.data : {};
    state.isLoginStatus = !!(userInfo.data && userInfo.data.teacher_id);
    if (!(state.userInfo && state.userInfo.teacher_id)) {
      router.push({ path: '/login', replace: false });
    }
  };
  const init = async () => {
    await gainUserInfo(); //获取用户信息
  };

  const myuserLogin = async (param: LoginParam): Promise<BaseResponse<Login>> => {
    let userInfo: BaseResponse<Login> = await userLogin(param);
    if (userInfo.code === 0) state.userInfo = userInfo.data.teacher_id ? userInfo.data : {};
    return userInfo;
  };

  const myuserRegister = async (param: LoginParam): Promise<BaseResponse<Login>> => {
    let userInfo: BaseResponse<Login> = await register(param);
    if (userInfo.code === 0) state.userInfo = userInfo.data.teacher_id ? userInfo.data : {};
    return userInfo;
  };

  const store: IUseUserInfoStore = {
    state,
    init,
    myuserLogin,
    myuserRegister
  };

  provide(useUserInfoSymbol, { ...store });

  return store;
};

/**
 *  * useUserInfoStore 用户hooks.
 * @function
 * @returns store extend IUseUserInfoStore
 */
export const useUserInfoStore: IUseUserInfoStoreFn = () => {
  const store: IUseUserInfoStore = inject(useUserInfoSymbol) as IUseUserInfoStore;
  return store;
};
